﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Security.Cryptography;
using System.IO;
using System.Reflection;
using System.Data.SqlClient;

namespace EnergyDB1
{
    public partial class coal_Form : Form
    {
        private int imgWidth = 16;
        private int imgHeight = 16;
        private Image imgExpand = Image.FromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream(@"EnergyDB1.Res.Expand.png"));
        private Image imgCollapse = Image.FromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream(@"EnergyDB1.Res.Collapse.png"));

        private int currentRowIndex;
        private int currentColumnIndex;

        public coal_Form()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //利用从indexes.sd中读取的xml语句创建XmlDocument
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.LoadXml(decrypt());

            XmlNodeList countryList = xmldoc.SelectNodes("/root/sc");
            foreach (XmlNode child in countryList)
            {
                XmlElement xe = (XmlElement)child;
                DataGridViewRow row = new DataGridViewRow();
                row.ContextMenuStrip = contextMenuStrip1;
                CollapseDataGridViewCell cell = new CollapseDataGridViewCell();
                cell.Value = xe.GetAttribute("name");
                cell.IsParent = true;
                row.Cells.Add(cell);
                dataGridView1.Rows.Add(row);

                XmlNodeList catergoryList = xe.ChildNodes;
                foreach (XmlNode catergory in catergoryList)
                {
                    drawNode(catergory, cell);
                }
            }
        }

        public void drawNode(XmlNode node, CollapseDataGridViewCell parentCell)
        {
            XmlElement xe = (XmlElement)node;
            XmlNodeList childList = node.ChildNodes;

            DataGridViewRow row = new DataGridViewRow();
            row.ContextMenuStrip = contextMenuStrip1;
            //第一列Description列
            CollapseDataGridViewCell cell = new CollapseDataGridViewCell();
            cell.Value = xe.GetAttribute("name");
            row.Cells.Add(cell);
            //第二列Identity列
            CollapseDataGridViewCell cell2 = new CollapseDataGridViewCell();
            cell2.Value = xe.GetAttribute("id");
            row.Cells.Add(cell2);
            row.Visible = false;                           //初始状态除最上层外，所有节点都隐藏
            parentCell.AddChildCell(cell);
            dataGridView1.Rows.Add(row);

            if (childList.Count != 0)                      //判断是否是最底层的指标
            {
                cell.IsParent = true;
                foreach (XmlNode child in childList)
                {
                    drawNode(child, cell);
                }
            }
            else
            {
                cell.IsParent = false;
            }
        }

        //从indexes.sd文件解析出描述指标的xml语句
        public string decrypt()
        {
            byte[] key = { 24, 55, 102, 24, 98, 26, 67, 29, 84, 19, 37, 118, 104, 85, 121, 27, 93, 86, 24, 55, 102, 24, 98, 26, 67, 29, 9, 2, 49, 69, 73, 92 };
            byte[] IV = { 22, 56, 82, 77, 84, 31, 74, 24, 55, 102, 24, 98, 26, 67, 29, 99 };
            RijndaelManaged myRijndael = new RijndaelManaged();
            FileStream fsOut = File.Open("../../Data/indexes.sd", FileMode.Open, FileAccess.Read);
            CryptoStream csDecrypt = new CryptoStream(fsOut, myRijndael.CreateDecryptor(key, IV), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(csDecrypt, System.Text.Encoding.Default);
            return sr.ReadToEnd();
        }

        //重写DataGridView的CellPainting事件
        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                using (Brush backColorBrush = new SolidBrush(e.CellStyle.BackColor), gridBrush = new SolidBrush(dataGridView1.GridColor))
                {
                    using (Pen gridLinePen = new Pen(gridBrush))
                    {
                        //如果该Cell位于第一列（Description列），则对其进行重绘
                        if (dataGridView1.Columns["Description"].Index == e.ColumnIndex)
                        {
                            CollapseDataGridViewCell cell = (CollapseDataGridViewCell)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                            //判断该Cell是否是父节点：如果是的话，需要绘制折叠图标；如果不是的话，需要绘制边框
                            if (cell.IsParent)
                            {
                                e.Graphics.FillRectangle(backColorBrush, e.CellBounds);

                                //绘制折叠图标
                                Rectangle rect = new Rectangle(e.CellBounds.Location.X + (cell.GroupLevel - 1) * imgWidth + 4, e.CellBounds.Location.Y + 4, imgWidth, imgHeight);
                                cell.PlusRect = rect;      //返回该Cell的折叠图标区域
                                if (cell.IsCollapsed)
                                {
                                    e.Graphics.DrawImage(imgCollapse, rect);
                                }
                                else
                                {
                                    e.Graphics.DrawImage(imgExpand, rect);
                                    //利用GroupLevel判断是否绘制下边框，有待改进
                                    if (cell.GroupLevel == 3)
                                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left + cell.GroupLevel * imgWidth + 4, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
                                }

                                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, Brushes.Black, e.CellBounds.X + cell.GroupLevel * imgWidth + 6, e.CellBounds.Y + 5, StringFormat.GenericDefault);
                            }
                            else
                            {
                                e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
                                e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left + (cell.GroupLevel - 1) * imgWidth + 4, e.CellBounds.Top - 1, e.CellBounds.Right - 1, e.CellBounds.Top - 1);                                     //上边框
                                e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left + (cell.GroupLevel - 1) * imgWidth + 4, e.CellBounds.Top - 1, e.CellBounds.Left + (cell.GroupLevel - 1) * imgWidth + 4, e.CellBounds.Bottom - 1);      //左边框
                                e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left + (cell.GroupLevel - 1) * imgWidth + 4, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);                               //下边框
                                e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);                                                              //右边框
                                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, Brushes.Black, e.CellBounds.X + (cell.GroupLevel - 1) * imgWidth + 6, e.CellBounds.Y + 5, StringFormat.GenericDefault);                    //表格内容
                            }
                        }
                        //如果该Cell不在第一列，但是与父节点位于同一行的话，则去除该Cell的边框
                        else if ((dataGridView1.Rows[e.RowIndex].Cells[0] as CollapseDataGridViewCell).IsParent)
                        {
                            e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
                            CollapseDataGridViewCell cell = (CollapseDataGridViewCell)dataGridView1.Rows[e.RowIndex].Cells[0];
                            if (!cell.IsCollapsed && cell.GroupLevel == 3)
                            {
                                e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left + 1, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
                            }
                        }
                        //如果该Cell既不在第一列，又不与父节点同行的话，则正常绘制该Cell
                        else
                        {
                            e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Top - 1, e.CellBounds.Right - 1, e.CellBounds.Top - 1);                         //上边框
                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);                   //下边框
                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);                 //右边框
                            e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, Brushes.Black, e.CellBounds.X + 6, e.CellBounds.Y + 5, StringFormat.GenericDefault);    //表格内容
                        }
                    }
                }
                if (dataGridView1.Rows[e.RowIndex].Selected)
                {
                    for (int i = 0; i < dataGridView1.Rows[e.RowIndex].Cells.Count; i++)
                    {
                        dataGridView1[i, e.RowIndex].Style.BackColor = Color.LightGray;
                    }
                }
                else
                {
                    for (int i = 0; i < dataGridView1.Rows[e.RowIndex].Cells.Count; i++)
                    {
                        dataGridView1[i, e.RowIndex].Style.BackColor = Color.Empty;
                    }
                }
                e.Handled = true;
            }
        }

        //双击展开子节点
        private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                CollapseDataGridViewCell cell = (CollapseDataGridViewCell)dataGridView1.Rows[e.RowIndex].Cells[0];
                if (cell.IsCollapsed)
                {
                    cell.Expand();
                }
                else
                {
                    cell.Collapse();
                }
            }
        }

        //右键选中行
        private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    if (dataGridView1.Rows[e.RowIndex].Selected == false)
                    {
                        dataGridView1.ClearSelection();
                        dataGridView1.Rows[e.RowIndex].Selected = true;
                    }
                }
            }
        }

        private void 查看数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int i = 1;
            Form form = new data_Form();
            form.MdiParent = this.MdiParent;
            DataGridView dgv = new DataGridView();

            String sql1 = "select a.timepoint";
            String sql2 = " from (select timepoint from xinhua.dbo.DimDate) as a ";

            String connString = "Data Source=172.16.157.142;Initial Catalog=xinhua;User Id=sa;Password=63077455;";
            SqlConnection conn = new SqlConnection(connString);
            conn.Open();

            foreach (Control ctl in form.Controls)
            {
                if (ctl is DataGridView)
                {
                    dgv = (DataGridView)ctl;
                    break;
                }
            }

            //添加时间点列
            DataGridViewColumn dgvc1 = new DataGridViewTextBoxColumn();
            dgv.Columns.Add(dgvc1);

            foreach (DataGridViewRow dgvr in dataGridView1.SelectedRows)
            {
                CollapseDataGridViewCell cdgvc = (CollapseDataGridViewCell)dataGridView1.Rows[dgvr.Index].Cells[0];
                if (!cdgvc.IsParent)
                {
                    DataGridViewColumn dgvc = new DataGridViewTextBoxColumn();
                    dgvc.HeaderText = (String)dgvr.Cells[0].Value;
                    dgvc.Name = "row" + i;
                    dgv.Columns.Add(dgvc);
                    sql1 += ", b" + i +".value";
                    sql2 += "left join (select SERIES_ID, TIMEPOINT, VALUE from xinhua.dbo.TSERIES_DATA where SERIES_ID = '" + (String)dgvr.Cells[1].Value + "') as b" + i + " on a.TIMEPOINT = b" + i + ".TIMEPOINT ";
                    i++;
                }
            }

            SqlCommand cmd = new SqlCommand(sql1+sql2+"order by a.timepoint", conn);
            SqlDataReader data = cmd.ExecuteReader();
            while(data.Read())
            {
                DataGridViewRow row = new DataGridViewRow();
                for (int j = 0; j < i; j++)
                {
                    DataGridViewTextBoxCell cell = new DataGridViewTextBoxCell();
                    cell.Value = data[j];
                    row.Cells.Add(cell);
                }
                dgv.Rows.Add(row);
            }

            form.Show();
        }

        void form_Load(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
        {
            currentRowIndex = e.RowIndex;
            currentColumnIndex = e.ColumnIndex;
        }

    }
}
